// 导入ApiService
import ApiService from './ApiService.js';

class ReviewStore {
  constructor() {
    this.reviews = [];
    this.listeners = [];
    this.isLoading = false;
    this.error = null;
    
    // 从localStorage加载数据作为初始数据
    this.loadFromStorage();
  }
  
  // 从API加载数据
  async loadReviews() {
    this.isLoading = true;
    this.error = null;
    try {
      const response = await ApiService.getReviews();
      if (response.success) {
        this.reviews = response.data;
        this.saveToStorage(); // 缓存到本地
        this.notifyListeners();
        return true;
      } else {
        throw new Error('Failed to load reviews');
      }
    } catch (error) {
      console.error('Failed to load reviews from API:', error);
      this.error = error.message || '加载评论数据失败';
      // 如果API失败，确保我们有数据可用
      if (this.reviews.length === 0) {
        this.loadFromStorage();
      }
      return false;
    } finally {
      this.isLoading = false;
    }
  }
  
  // 添加监听器
  addListener(listener) {
    this.listeners.push(listener);
  }
  
  // 移除监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }
  
  // 通知所有监听器数据已更新
  notifyListeners() {
    this.listeners.forEach(listener => listener());
  }
  
  // 保存数据到localStorage
  saveToStorage() {
    localStorage.setItem('reviewsData', JSON.stringify(this.reviews));
  }
  
  // 从localStorage加载数据
  loadFromStorage() {
    const savedData = localStorage.getItem('reviewsData');
    if (savedData) {
      try {
        this.reviews = JSON.parse(savedData);
      } catch (e) {
        console.error('Failed to load reviews from localStorage:', e);
      }
    } else {
      // 如果没有缓存数据，使用默认数据
      this.reviews = [
        {
          id: 1,
          productId: 1,
          customerId: 1,
          customerName: '张三',
          rating: 5,
          content: '这款无人机非常棒！续航能力强，操作简单，画质清晰，强烈推荐！',
          createdAt: '2023-11-15T10:30:00',
          reply: null
        },
        {
          id: 2,
          productId: 2,
          customerId: 2,
          customerName: '李四',
          rating: 4,
          content: '无人机性能不错，不过价格稍微有点高，整体来说物有所值。',
          createdAt: '2023-11-14T14:20:00',
          reply: {
            content: '感谢您的评价！我们一直致力于提供高性价比的产品，如有任何问题请随时联系我们。',
            createdAt: '2023-11-14T15:00:00'
          }
        },
        {
          id: 3,
          productId: 3,
          customerId: 3,
          customerName: '王五',
          rating: 3,
          content: '无人机总体还行，但是电池续航没有宣传的那么长，希望后续能改进。',
          createdAt: '2023-11-13T09:15:00',
          reply: null
        },
        {
          id: 4,
          productId: 1,
          customerId: 4,
          customerName: '赵六',
          rating: 5,
          content: '第一次使用无人机，上手很快，飞了好几次都很稳定，值得购买！',
          createdAt: '2023-11-12T16:45:00',
          reply: {
            content: '很高兴听到您对我们产品的满意！如有任何使用问题，请查看我们的使用手册或联系客服。',
            createdAt: '2023-11-13T10:00:00'
          }
        },
        {
          id: 5,
          productId: 4,
          customerId: 5,
          customerName: '钱七',
          rating: 2,
          content: '无人机收到时有一点损坏，联系客服后处理还算及时，但影响了使用体验。',
          createdAt: '2023-11-11T20:10:00',
          reply: {
            content: '非常抱歉给您带来不好的体验！我们已经安排客服专员与您联系，将为您提供满意的解决方案。',
            createdAt: '2023-11-12T09:30:00'
          }
        },
        {
          id: 6,
          productId: 5,
          customerId: 6,
          customerName: '孙八',
          rating: 4,
          content: '工业级无人机确实专业，功能强大，就是有点重，携带不是很方便。',
          createdAt: '2023-11-10T11:30:00',
          reply: null
        },
        {
          id: 7,
          productId: 6,
          customerId: 7,
          customerName: '周九',
          rating: 5,
          content: '电池质量很好，续航能力强，比原装的还要好，已经是第二次购买了。',
          createdAt: '2023-11-09T13:20:00',
          reply: {
            content: '感谢您的支持和信任！我们会继续努力提供优质的产品和服务。',
            createdAt: '2023-11-09T14:00:00'
          }
        }
      ];
    }
  }
  
  // 获取所有评论
  getAllReviews() {
    return [...this.reviews];
  }
  
  // 根据ID获取评论
  getReviewById(id) {
    return this.reviews.find(review => review.id === id);
  }
  
  // 根据产品ID获取评论
  getReviewsByProductId(productId) {
    return this.reviews.filter(review => review.productId === productId);
  }
  
  // 根据客户ID获取评论
  getReviewsByCustomerId(customerId) {
    return this.reviews.filter(review => review.customerId === customerId);
  }
  
  // 根据评分获取评论
  getReviewsByRating(rating) {
    return this.reviews.filter(review => review.rating === rating);
  }
  
  // 添加评论（用于测试）
  async addReview(review) {
    try {
      const response = await ApiService.addReview(review);
      if (response.success) {
        this.reviews.push(response.data);
        this.saveToStorage();
        this.notifyListeners();
        return response.data;
      } else {
        throw new Error('Failed to add review');
      }
    } catch (error) {
      console.error('Failed to add review via API:', error);
      // API失败时的降级处理
      const newId = Math.max(0, ...this.reviews.map(r => r.id)) + 1;
      const newReview = {
        id: newId,
        ...review
      };
      this.reviews.push(newReview);
      this.saveToStorage();
      this.notifyListeners();
      return newReview;
    }
  }
  
  // 更新评论（回复评论）
  async updateReview(id, updatedReview) {
    try {
      const response = await ApiService.updateReview(id, updatedReview);
      if (response.success) {
        const index = this.reviews.findIndex(r => r.id === id);
        if (index !== -1) {
          this.reviews[index] = response.data;
          this.saveToStorage();
          this.notifyListeners();
          return response.data;
        }
      } else {
        throw new Error('Failed to update review');
      }
    } catch (error) {
      console.error('Failed to update review via API:', error);
      // API失败时的降级处理
      const index = this.reviews.findIndex(r => r.id === id);
      if (index !== -1) {
        this.reviews[index] = {
          ...this.reviews[index],
          ...updatedReview
        };
        this.saveToStorage();
        this.notifyListeners();
        return this.reviews[index];
      }
    }
    return null;
  }
  
  // 删除评论
  async deleteReview(id) {
    try {
      const response = await ApiService.deleteReview(id);
      if (response.success) {
        const initialLength = this.reviews.length;
        this.reviews = this.reviews.filter(review => review.id !== id);
        
        if (this.reviews.length !== initialLength) {
          this.saveToStorage();
          this.notifyListeners();
          return true;
        }
      } else {
        throw new Error('Failed to delete review');
      }
    } catch (error) {
      console.error('Failed to delete review via API:', error);
      // API失败时的降级处理
      const initialLength = this.reviews.length;
      this.reviews = this.reviews.filter(review => review.id !== id);
      
      if (this.reviews.length !== initialLength) {
        this.saveToStorage();
        this.notifyListeners();
        return true;
      }
    }
    return false;
  }
  
  // 搜索评论
  searchReviews(query) {
    if (!query) {
      return this.getAllReviews();
    }
    
    const lowerQuery = query.toLowerCase();
    return this.reviews.filter(review => 
      review.content.toLowerCase().includes(lowerQuery) ||
      review.customerName.toLowerCase().includes(lowerQuery)
    );
  }
  
  // 获取评论统计数据
  async getReviewStats() {
    try {
      const response = await ApiService.getReviewStats();
      if (response.success) {
        return response.data;
      } else {
        throw new Error('Failed to get review stats');
      }
    } catch (error) {
      console.error('Failed to get review stats via API:', error);
      // API失败时，本地计算统计数据
      const totalReviews = this.reviews.length;
      const avgRating = totalReviews > 0 ? this.reviews.reduce((sum, review) => sum + review.rating, 0) / totalReviews : 0;
      const reviewsByRating = {};
      
      for (let i = 1; i <= 5; i++) {
        reviewsByRating[i] = this.reviews.filter(review => review.rating === i).length;
      }
      
      return {
        totalReviews,
        avgRating: avgRating.toFixed(1),
        reviewsByRating
      };
    }
  }
  
  // 获取最近的评论
  getRecentReviews(limit = 5) {
    return [...this.reviews]
      .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      .slice(0, limit);
  }
}

// 创建单例实例
export default new ReviewStore();